﻿using AJWPFAdmin.Core.Crypto.SMCrypto;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Logger;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.AppointAPI.Qingdao;
using AJWPFAdmin.Services.AppointAPI.Qingdao.Model;
using AJWPFAdmin.Services.EF;
using Masuit.Tools;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Prism.Ioc;
using System;

namespace AJWPFAdmin.Services.AppointAPI
{
    public class GetQingdaoToken
    {
        private readonly IQingdaoApiImplement _apiImplement;
        private readonly IBaseNonTableCache<QingdaoGetTokenRes> _cache;
        private AJLog4NetLogger _logger;
        private IContainerProvider _svcProvider;
        public GetQingdaoToken(IQingdaoApiImplement apiImplement, IBaseNonTableCache<QingdaoGetTokenRes> cache, AJLog4NetLogger logger, IContainerProvider svcProvider)
        {
            _apiImplement = apiImplement;
            _cache = cache;
            _logger= logger;
            _svcProvider= svcProvider;
        }

        public string GetConfig()
        {
            using var db = DbService.GetDbContext(_svcProvider.Resolve<AJConfigService>());

            var cfg = db.SystemConfigDictionaries.AsNoTracking()
                .FirstOrDefault(p => p.Key >= SystemConfigKey.APIQingDao);
            if(cfg!=null)
            {
               return cfg.StringValue;
            }
            return string.Empty;
        }

        public QingdaoBaseConfig GetApiConfig()
        {
          var cfg=GetConfig();
            if (cfg == default)
            {
                return new QingdaoBaseConfig();
            }
            else
            {
               return CommonUtil.TryGetJSONObject<QingdaoBaseConfig>(cfg);
            }
        }

        /// <summary>
        /// 获取api的token
        /// </summary>
        /// <returns></returns>

        public async Task<string> GetToken()
        {
            var token=await _cache.GetOrSetStringCache(GetTokenFromApiAsync,null, 11 * 60 * 60);
            if (string.IsNullOrWhiteSpace(token))
            {
                return string.Empty;
            }
            return token;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        /// <exception cref="MyException"></exception>
        public async Task<string> GetTokenFromApiAsync()
        {
            var configString = GetConfig();
            if (string.IsNullOrWhiteSpace(configString))
            {
                _logger.Error("QingdaoAppointAPI--GetTokenFromApiAsync--error GetConfig return null ");
                return null;
            }
            var baseConfig = CommonUtil.TryGetJSONObject<QingdaoBaseConfig>(configString);
            var req = CommonUtil.TryGetJSONObject<QingdaoGetTokenReq>(configString);
            var reqWrapped = new QingdaoBaseCommonReq { encryptData = SM2.EncryptToBase64(CommonUtil.AJSerializeObject(req), baseConfig.publicKey),source= baseConfig.clientId,version=baseConfig.version };
            var res = await _apiImplement.GetToken(reqWrapped);
            if (res.Code != 200)
            {
                _logger.Error($"GetQingdaoToken-获取token失败：状态码:{res.Code}，失败信息:{res.Msg}");
                return null;
            }
            var resWrapped = SM2.Decrypt(Convert.FromBase64String(res.encryptData), baseConfig.privateKey);
            var tokenRes = CommonUtil.TryGetJSONObject<QingdaoGetTokenRes>(resWrapped);
            if (tokenRes.Code != 200)
            {
                _logger.Error($"GetQingdaoToken-获取token失败：解密状态码:{res.Code}，解析错误信息:{res.Msg}");
                return null;
            }
            _cache.SetStringCache(tokenRes.Data.access_token, null, 11 * 60 * 60);
            return tokenRes.Data.access_token;
        }
    }
}
